import React from 'react';
import {
  Form,
  DatePicker,
  Select,
  InputNumber,
  Radio,
  Button,
  Row,
  Col, Icon,
} from 'antd';
import styles from './MileageDataFilter.less';
import moment from "moment";
import locale from 'antd/lib/date-picker/locale/zh_CN';
import 'moment/locale/zh-cn';
import {fetchMileageReportData} from "../../services/report";
import {getTimeDistance} from "../../utils/utils";
import {fetchLatestStaysList} from "../../services/map";
import {fetchDeviceList} from "../../services/device";
import {connect} from "react-redux";
import {FETCH_DEVICES} from "../../models/device/const";
import getDeviceList from "../../models/selectors";
import MyDeviceTypeSelect from "../MyDeviceTypeSelect";
import {CHANGE_QUERY_TIME} from "../../models/report/const";

moment.locale('zh-cn');

const FormItem = Form.Item;
const Option = Select.Option;
const {RangePicker} = DatePicker;

@connect(({device, report}) => {
  const deviceList = getDeviceList(device) || [];
  const deviceIdList = deviceList.map(item => {
    return {
      device_id:item.device_id,
      device_name: item.device_name
    }
  });
  const {queryTime} = report;
  return ({deviceIdList, queryTime})
})
@Form.create()
class MileageDataFilter extends React.Component {
  state = {
    expandForm: true,
    isCustomTime: false,
  };
  handleFormReset = () => {
    const {
      form: {resetFields},
    } = this.props;
    resetFields();
  };

  async componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: FETCH_DEVICES,
    });
    window.addEventListener('keydown', this.handleKeyDown)
  }

  handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      this.handleSubmit(e)
    }
  };

  idToName=(id)=>{
    this.props.deviceIdList.forEach(function (item) {
      if(item.device_id===id){
        if(item.device_name){
          id=item.device_name;
        }
      }
    });
    return id;
  };

  componentWillUnmount() {
    window.removeEventListener('keydown', this.handleKeyDown)
  }

  static getDerivedStateFromProps(props, state) {
    const {
      queryTime
    } = props;
    if (queryTime !== null) {
      return {isCustomTime: true}
    }
    return null;
  }

  handlerSetState = state => _ => {
    if (state.isCustomTime) {
      const {
        form: {setFieldsValue},
      } = this.props;
      setFieldsValue({dateSelect: ''})
    }else{
      const {dispatch, queryTime} = this.props;
      if (queryTime) {
        dispatch({type: CHANGE_QUERY_TIME, payload: null})
      }
    }
    this.setState(state);
  };

  handleSubmit = e => {
    e.preventDefault();
    const {form: {getFieldsValue}, onFetch} = this.props;
    const {
      dateSelect,
      device,
      minTime,
      rangeTimePicker,
      type,
    } = getFieldsValue();

    let timeSection = rangeTimePicker;
    if (!timeSection) {
      timeSection = getTimeDistance(dateSelect)
    }
    const start_time = Math.floor(timeSection[0].valueOf() / 1e3);
    const end_time = Math.floor(timeSection[1].valueOf() / 1e3);
    const params = {device_id: device, type, start_time, end_time, min_stay_time: minTime};
    onFetch(params);
  };

  handleTypeChange = type => {
    const {
      form: {setFieldsValue,},
    } = this.props;
    switch (type) {
      case 'detail':
        const {deviceList} = this.props;
        // setFieldsValue({'device': deviceList[0],});
        // todo remove
        setFieldsValue({'device': '4574',});
        return type;
      default:
        setFieldsValue({'device': '',});
        return type
    }
  };


  renderAdvancedForm = () => {
    const {
      form: {getFieldDecorator, getFieldValue,},
      queryTime
    } = this.props;

    const {isCustomTime,} = this.state;
    const {deviceIdList,} = this.props;

    let getDefaultDate = () => {};
    let dateSelectInitialValue = 'yesterday';
    if (queryTime) {
      const {start_time, end_time} = queryTime;
      dateSelectInitialValue = '';
      getDefaultDate = _ => [moment(start_time * 1e3), moment(end_time * 1e3)];
    } else {
      getDefaultDate = _ => [moment().subtract(1, 'days'), moment()];
    }
    const defaultValue = getDefaultDate();

    const reportType = getFieldValue('type');
    // todo fix
    const dateTypeList = ['day', 'detail'];

    return (
      <Form onSubmit={this.handleSubmit} layout="inline" >
        <Row gutter={{md: 8, lg: 24, xl: 48}} justify="start" type="flex" >
          {/*<Col lg={6} md={6} sm={24}>*/}
          {/*  <FormItem label="报表类型">*/}
          {/*    {getFieldDecorator('type', {initialValue: 'day', getValueFromEvent: this.handleTypeChange})(*/}
          {/*        <Select placeholder="请选择" style={{width: '100%'}}>*/}
          {/*          <Option value="detail">明细</Option>*/}
          {/*          <Option value="day">日报</Option>*/}
          {/*          <Option value="week">周报</Option>*/}
          {/*          <Option value="month">月报</Option>*/}
          {/*        </Select>*/}
          {/*    )}*/}
          {/*  </FormItem>*/}
          {/*</Col>*/}
          {

            <Col lg={9} md={12} sm={24} >
              <FormItem label="时间选择">
                {getFieldDecorator('dateSelect', {initialValue: dateSelectInitialValue})(
                    <Radio.Group onChange={this.handlerSetState({isCustomTime: false})}>
                      <Radio.Button value="yesterday">昨天</Radio.Button>
                      <Radio.Button value="today">今天</Radio.Button>
                      <Radio.Button value="2days">近2天</Radio.Button>
                      <Radio.Button value="7days">近7天</Radio.Button>
                      <Radio.Button value="10days">近10天</Radio.Button>
                    </Radio.Group>
                )}
              </FormItem>
            </Col>
          }
          <Col xl={9} md={12} sm={24} >
            {
              isCustomTime ?
                  (<FormItem label="选择">
                    {getFieldDecorator('rangeTimePicker', {initialValue: defaultValue})(
                        <RangePicker
                            locale={locale}
                            showTime={{format: 'HH:mm'}}
                            format="YYYY-MM-DD HH:mm"
                            placeholder={['Start Time', 'End Time']}
                        />
                    )}
                  </FormItem>) :
                  <a style={{marginLeft: -20,}} onClick={this.handlerSetState({isCustomTime: true})}>
                    自定义时间 <Icon type="date"/>
                  </a>
            }
          </Col>
        </Row>

        <Row gutter={{md: 8, lg: 24,}} justify="start" type="flex">
          {/*<Col md={6} sm={24}>*/}
          {/*  <MyDeviceTypeSelect isFormItem style={{width: '100%'}}/>*/}
          {/*</Col>*/}

          {/*<Col md={6} sm={24}>*/}
          {/*  <FormItem label="设备选择">*/}
          {/*    {getFieldDecorator('device')(*/}
          {/*        <Select placeholder="可选" style={{width: '100%'}}>*/}
          {/*          /!*<Option key={'device'} value={''}>&nbsp;</Option>*!/*/}
          {/*          {*/}
          {/*            deviceIdList.map(device => (<Option key={device.device_id} value={device.device_id}>{this.idToName(device.device_id)}</Option>)*/}
          {/*            )*/}
          {/*          }*/}
          {/*        </Select>*/}
          {/*    )}*/}
          {/*  </FormItem>*/}
          {/*</Col>*/}

          {/*<Col md={8} sm={24}>*/}
          {/*<FormItem label="停留时间 (大于等于)">*/}
          {/*{getFieldDecorator('minTime', {initialValue: 1})(<InputNumber*/}
          {/*style={{width: '100%'}}*/}
          {/*formatter={value => `${value}分钟`}*/}
          {/*parser={value => value.replace('分钟', '')}*/}
          {/*/>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}

        </Row>
        <div style={{overflow: 'hidden'}}>
          <div style={{float: 'right', marginBottom: 24}}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
              重置
            </Button>
          </div>
        </div>
      </Form>
    );
  };


  renderForm() {
    const {expandForm} = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    return (
      <div>
        <div className={styles.tableListForm}>{this.renderForm()}</div>
      </div>
    )
  }
}


export default MileageDataFilter;
